package com.example.private_auto_install.toolby;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public abstract class RSADeCoder {
    public static final String KEY_ALGORITHM = "RSA";
    public static final String KEY_PROVIDER = "BC";
    public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";

    public RSADeCoder() {
    }

    public static byte[] decryptRSA(byte[] encoderData, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA", "BC");
        cipher.init(2, publicKey);
        int blockSize = cipher.getBlockSize();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        for(int j = 0; encoderData.length - j * blockSize > 0; ++j) {
            bout.write(cipher.doFinal(encoderData, j * blockSize, blockSize));
        }

        return bout.toByteArray();
    }

    public static boolean verify(byte[] encoderData, String sign, PublicKey publicKey) throws Exception {
        Signature sig = Signature.getInstance("SHA1WithRSA", "BC");
        sig.initVerify(publicKey);
        sig.update(encoderData);
        return sig.verify(Base64.decodeBase64(sign.getBytes()));
    }

    public static PublicKey getPublicKey(String modulus, String exponent) throws Exception {
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        Security.addProvider(new BouncyCastleProvider());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
        return (RSAPublicKey)keyFactory.generatePublic(keySpec);
    }
}